#include "MeshToObjWriter.h"
#include "VertexList.h"
#include "ObjMesh.h"
#include "IndexBufferMaterial.h"
#include "TriangleList.h"
MeshToObjWriter::MeshToObjWriter(tstring filename):TextWriter(filename)
{
}

MeshToObjWriter::~MeshToObjWriter(void)
{
}

bool MeshToObjWriter::WriteMesh(ObjMesh* mesh)
{
	Open();
	
	VertexList* pVertexList = mesh->GetVertexList();
	int posoffset = pVertexList->GetOffset(POSITION);
	int normoffset = pVertexList->GetOffset(NORMAL);
	int tcoffset = pVertexList->GetOffset(TEXCOORD);
	
	int nrOfVertices = pVertexList->GetSize();
	for (int i =0 ; i< nrOfVertices; ++i){
		DAEFloat3 vertex;
		pVertexList->GetVertexData(i,posoffset,&vertex);
		m_Output<< _T("v ") << vertex.x<<" "<<vertex.y<<" " <<vertex.z<< endl;
	}
	this->WriteEndl();
	for (int i =0 ; i< nrOfVertices; ++i){
		DAEFloat3 vertex;
		pVertexList->GetVertexData(i, normoffset,&vertex);
		m_Output<< _T("vn ") << vertex.x<<" "<<vertex.z<<" " <<vertex.y<< endl;
	}
	this->WriteEndl();
	for (int i =0 ; i< nrOfVertices; ++i){
		DAEFloat2 vertex;
		pVertexList->GetVertexData(i, tcoffset,&vertex);
		m_Output<< _T("vt ") << vertex.x<<" "<<(1-vertex.y)<< endl;
	}
	m_Output<<_T("g ")<< mesh->GetName() << endl;

	IBMIT indices;
	for (indices = mesh->GetBegin(); indices != mesh->GetEnd(); ++indices)
	{
		IndexBufferMaterial* indexbuffer = *indices;
		IndexedGeometry* indices = indexbuffer->GetIndexBuffer();

		TriangleList* triangles = dynamic_cast<TriangleList*>(indices);
		if ( triangles != NULL ){
			for (int i = 0; i < triangles->GetNumberOfPrimitives() ;++i)
			{
				m_Output << _T("f ");
				int i1,i2,i3;
				triangles->GetIndexedFace(i,&i1,&i2,&i3);
				++i1;
				++i2;
				++i3;
				m_Output << i1 << _T("/") << i1 << _T("/") << i1 << " ";
				m_Output << i2 << _T("/") << i2 << _T("/") << i2 << " ";
				m_Output << i3 << _T("/") << i3 << _T("/") << i3 << endl;
			}
		}
	}

	Close();
	return true;
}